#import "XMRCManager.h"
#import "RCIM.h"

@implementation XMRCManager

+ (XMRCManager *)sharedInstance {
    static XMRCManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)connectWithToken:(NSString *)token
               timeLimit:(int)timeLimit
                dbOpened:(void (^)(RCDBErrorCode code))dbOpenedBlock
                 success:(void (^)(NSString *userId))successBlock
                   error:(void (^)(RCConnectErrorCode errorCode))errorBlock {
    [[RCIM sharedRCIM] connectWithToken:token
        timeLimit:timeLimit
        dbOpened:^(RCDBErrorCode code) {
            XMLog(@"消息数据库打开，可以进入到主页面");
            dbOpenedBlock(code);
        }
        success:^(NSString *userId) {
        XMLog(@"连接成功");
            successBlock(userId);
        }
        error:^(RCConnectErrorCode status) {
            errorBlock(status);
            if (status == RC_CONN_TOKEN_INCORRECT) {
                XMLog(@"token 非法，从 APP 服务获取新 token，并重连");
            } else if (status == RC_CONNECT_TIMEOUT) {
                XMLog(@"连接超时，弹出提示，可以引导用户等待网络正常的时候再次点击进行连接");
            } else {
                XMLog(@"无法连接 IM 服务器，请根据相应的错误码作出对应处理");
            }
        }];
}

- (void)updateUserCacheUserId:(NSString *)userId
                             alias:(NSString *)alias
                              name:(NSString *)name
                       portraitUri:(NSString *)portraitUri
                             extra:(NSString *)extra {
    RCUserInfo *user = [[RCIM sharedRCIM] getUserInfoCache:userId];
    if (![NSString isEmpty:alias]) {
        user.alias = alias;
    }
    if (![NSString isEmpty:name]) {
        user.name = name;
    }
    if (![NSString isEmpty:portraitUri]) {
        user.portraitUri = portraitUri;
    }
    if (![NSString isEmpty:extra]) {
        user.extra = extra;
    }
    [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:userId];
}
@end
